// dati.js
// 获取app实例
const app = getApp();

Page({
  data: {
    list: [1, 2, 3, 3, 3, 3, 3],
    question_num: "",
    showtan: false,
    showmsg: false,
    totalHeaderHeightall: "",
    showJiucuoModal: false, // 控制纠错弹窗显示
    showDatikaModal: false, // 控制答题卡弹窗显示
    showPinglunModal: false, // 控制评论弹窗显示
    // 轮播图数据
    banners: [
      {
        id: 3,
        image: 'https://exam-1304576422.cos.ap-guangzhou.myqcloud.com/static/banner.png',
        url: ''
      },
      {
        id: 1,
        image: 'https://exam-1304576422.cos.ap-guangzhou.myqcloud.com/static/banner1.png',
        url: ''
      },
      // {
      //   id: 2,
      //   image: 'https://exam-1304576422.cos.ap-guangzhou.myqcloud.com/static/banner2.png',
      //   url: ''
      // }
    ],
    currentBannerIndex: 0,
    // AI问答相关数据
    inputValue: '',
    messages: [],
    isLoading: false,
    isFirstQuestion: true,
    singleChoiceQuestions: Array.from({ length: 12 }, (_, i) => i + 1), // 单选题数据
    multipleChoiceQuestions: Array.from({ length: 12 }, (_, i) => i + 1), // 多选题数据
    currentQuestion: null, // 当前题目详情
    questionId: '', // 题目ID，改为字符串类型以支持复合格式
    feedbackContent: '', // 纠错反馈内容
    selectedOption: null, // 选中的选项（单选题）
    selectedOptions: [], // 选中的选项（多选题）
    isAnswered: false, // 是否已提交答案
    isCorrect: false, // 答案是否正确
    userAnswer: null, // 用户提交的答案
    answerCardId: '', // 答题卡ID
    questionIndex: 0, // 当前题目索引
    subjectId: '', // 科目ID
    chapterId: '', // 章节ID
    answerRecords: [], // 答题记录列表
    totalQuestions: 0, // 总题目数
    answeredCount: 0, // 已答题目数
    answerCardDetail: null, // 答题卡详情数据
    questionType: '单选题', // 题目类型，默认为单选题
    questionTypeCode: 0, // 题目类型代码
    isInErrorBook: false, // 是否在错题本中
    commentList: {}, // 评论列表（改为对象，方便按题目ID存储）
    commentLoading: {}, // 评论列表加载状态（改为对象）
    commentPage: 1, // 评论当前页码
    commentLimit: 10, // 评论每页数量
    commentTotal: 0, // 评论总数
    showComments: {}, // 控制是否显示评论
    currentQuestionId: '', // 当前评论的题目ID
    submitButtonText: '提交答案' // 提交按钮文字
  },
  onGuanggaoTap: function () {
    wx.navigateTo({
      url: '/pages/share/share'
    });
  },

  /**
   * 轮播图切换事件
   */
  onBannerChange: function (e) {
    console.log(e.detail.current)
    this.setData({
      currentBannerIndex: e.detail.current
    });
    this.setData({
      questionId: this.data.answerRecords[e.detail.current].id
    })
  },



  clearthis: function () {
    this.setData({
      types: "",
      showtan: false,
      tishititle: "",
      tishimessage: "",
    })
  },
  queren: function () {
    this.setData({
      types: "",
      showtan: false,
      tishititle: "",
      tishimessage: "",
    })
    wx.navigateTo({
      url: '/service/activity-quiz/activity-quiz'
    });
  },
  /**
   * 点击轮播图
   */
  onBannerTap: function (e) {
    const { index } = e.currentTarget.dataset;
    const banner = this.data.banners[index];

    // 如果有跳转链接则跳转，否则执行原广告点击逻辑
    if (banner.url) {
      wx.navigateTo({
        url: banner.url
      });
    } else {
      this.onGuanggaoTap();
    }
  },
  /**
   * 切换评论显示状态
   */
  toggleComments: function (e) {
    const questionId = e.currentTarget.dataset.questionId;
    const showComments = { ...this.data.showComments };

    // 如果当前题目评论未显示，则加载评论
    if (!showComments[this.data.currentBannerIndex]) {
      this.loadCommentList(questionId);
    }

    // 切换显示状态
    showComments[this.data.currentBannerIndex] = !showComments[this.data.currentBannerIndex];
    this.setData({
      showComments: showComments
    });
  },

  /**
   * 通过问题加载评论列表
   */
  loadCommentList: function (questionId) {
    const that = this;

    if (!questionId) {
      return;
    }

    // 设置加载状态
    const newCommentLoading = { ...this.data.commentLoading };
    newCommentLoading[this.data.currentBannerIndex] = true;
    this.setData({
      commentLoading: newCommentLoading
    });

    try {
      // 调用API获取评论列表
      app.api.getCommentList({
        questionId: questionId,
        page: 1,
        limit: 10
      }).then(res => {
        if (res && res.code === 200 && res.data) {
          const commentData = res.data;
          console.log('评论数据:', commentData);

          // 格式化评论数据
          const formattedComments = commentData.data.map(comment => ({
            id: comment.id,
            content: comment.content,
            likeCount: comment.like_count || 0,
            createTime: that.formatTime(comment.created_at),
            user: comment.user || {
              id: 0,
              nickname: '匿名用户',
              avatar: 'https://exam-1304576422.cos.ap-guangzhou.myqcloud.com/static/default_avatar.png'
            }
          }));

          // 查找对应题目的索引
          const questionIndex = that.data.answerRecords.findIndex(record => record.questionId === questionId);
          if (questionIndex !== -1) {
            // 更新answerRecords中对应题目的评论列表
            const newAnswerRecords = [...that.data.answerRecords];
            newAnswerRecords[this.data.currentBannerIndex].commentList = formattedComments;

            that.setData({
              answerRecords: newAnswerRecords
            });
          }
        }

        // 无论成功失败，都设置加载状态为false
        const updatedCommentLoading = { ...that.data.commentLoading };
        updatedCommentLoading[questionId] = false;
        that.setData({
          commentLoading: updatedCommentLoading
        });
      }).catch(err => {
        console.error('加载评论列表失败:', err);

        // 加载失败，设置默认评论数据
        that.setDefaultCommentData(questionId);

        // 设置加载状态为false
        const updatedCommentLoading = { ...that.data.commentLoading };
        updatedCommentLoading[questionId] = false;
        that.setData({
          commentLoading: updatedCommentLoading
        });
      });
    } catch (error) {
      console.error('加载评论出错:', error);
      // 设置加载状态为false
      const updatedCommentLoading = { ...this.data.commentLoading };
      updatedCommentLoading[questionId] = false;
      this.setData({
        commentLoading: updatedCommentLoading
      });
    }
  },

  /**
   * 设置默认评论数据
   */
  setDefaultCommentData: function (questionId) {
    const defaultComments = [
      {
        id: 0,
        content: '暂时没有评论，快来发表第一条评论吧！',
        likeCount: 0,
        createTime: this.formatTime(new Date()),
        user: {
          id: 0,
          nickname: '系统提示',
          avatar: 'https://exam-1304576422.cos.ap-guangzhou.myqcloud.com/static/default_avatar.png'
        }
      }
    ];

    // 查找对应题目的索引
    const questionIndex = this.data.answerRecords.findIndex(record => record.questionId === questionId);
    if (questionIndex !== -1) {
      // 更新answerRecords中对应题目的评论列表
      const newAnswerRecords = [...this.data.answerRecords];
      newAnswerRecords[questionIndex].commentList = defaultComments;

      this.setData({
        answerRecords: newAnswerRecords
      });
    }
  },

  /**
   * 格式化时间函数
   */
  formatTime: function (date) {
    if (!date) return '';

    // 如果是时间戳或字符串，转换为Date对象
    if (typeof date === 'number' || typeof date === 'string') {
      date = new Date(date);
    }

    // 检查是否为有效的Date对象
    if (!(date instanceof Date) || isNaN(date.getTime())) {
      return '';
    }

    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');

    return `${year}-${month}-${day} ${hours}:${minutes}`;
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 加载活动数据
    this.loadActivityData();
    // 加载活动详情
    this.loadActivityDetail();

    // 更严格的参数验证：只有当answerCardId是有效数字时才设置
    const answerCardId = options.answerCardId;
    const isValidAnswerCardId = answerCardId && !isNaN(parseInt(answerCardId)) && parseInt(answerCardId) > 0;

    this.setData({
      totalHeaderHeightall: app.globalData?.totalHeaderHeight,
      questionId: 0, // 初始化为0，后续从答题卡数据中获取
      answerCardId: isValidAnswerCardId ? parseInt(answerCardId) : '', // 答题卡ID，只接受有效数字
      questionIndex: parseInt(options.questionIndex) || 0, // 当前题目索引
      subjectId: options.subjectId || '', // 科目ID
      chapterId: options.chapterId || '', // 章节ID
      selectedOption: null, // 初始化选中的选项（单选题）
      selectedOptions: [], // 初始化选中的选项（多选题）
      isAnswered: false, // 初始化未提交答案状态
      isCorrect: false, // 初始化答案正确性状态
      userAnswer: null, // 初始化用户答案
      submitButtonText: '提交答案', // 初始化提交按钮文字
      activityDetail: null, // 活动详情
      loading: true // 加载状态
    });
  },

  /**
   * 加载活动详情数据
   */
  loadActivityDetail: function () {
    const that = this;

    wx.showLoading({
      title: '加载活动详情...',
      mask: true
    });

    // 调用获取活动详情接口，获取活动id=1的详情
    app.api.getActivityDetail({ activity_id: 1 })
      .then(res => {
        console.log('获取活动详情成功:', res);
        if (res && res.code === 200 && res.data) {
          // 尝试解析活动描述为JSON
          let activityDesc = res.data.activity_desc;
          if (activityDesc && typeof activityDesc === 'string') {
            try {
              activityDesc = JSON.parse(activityDesc);
            } catch (e) {
              console.error('解析活动描述失败:', e);
              // 如果解析失败，保留原始字符串
            }
          }

          // 处理嵌套的rules数组 - 转换为可直接在页面使用的格式
          if (activityDesc && activityDesc.rules && Array.isArray(activityDesc.rules)) {
            // 将rules数组直接作为activity_desc，使其可以被页面直接遍历
            activityDesc = activityDesc.rules;

            // 处理文本高亮 - 标记关键词
            activityDesc = activityDesc.map(item => {
              if (item.content) {
                // 定义需要高亮的关键词
                const highlightKeywords = ['20道', '小奖品', '发现题目错误', '纠正也有奖'];
                let highlightedContent = item.content;

                // 为每个关键词添加高亮标记
                highlightKeywords.forEach(keyword => {
                  // 使用正则表达式全局替换关键词，添加<span>标签
                  const regex = new RegExp(keyword, 'g');
                  highlightedContent = highlightedContent.replace(regex, `<span style="color: #D52718">${keyword}</span>`);
                });

                return {
                  ...item,
                  highlightedContent: highlightedContent
                };
              }
              return item;
            });
          }

          // 将获取到的活动详情存储到页面数据中
          that.setData({
            activityDetail: {
              ...res.data,
              activity_desc: activityDesc
            }
          });
        }
      })
      .catch(err => {
        console.error('获取活动详情失败:', err);
        wx.showToast({
          title: '活动详情加载失败',
          icon: 'none'
        });
      })
      .finally(() => {
        wx.hideLoading();
        that.setData({ loading: false });
      });
  },

  /**
   * 加载活动问题列表数据
   */
  loadActivityData: function () {
    const that = this;

    wx.showLoading({
      title: '加载活动问题列表...',
      mask: true
    });

    // 调用获取活动问题列表接口，获取活动id=1的问题列表
    app.api.getActivityQuestionList({ activity_id: 1 })
      .then(res => {
        console.log('获取活动问题列表成功:', res);
        if (res && res.code === 200 && res.data && res.data.list) {
          // 将获取到的活动问题列表存储到页面数据中
          that.setData({
            activityQuestionList: res.data.list,
            totalQuestions: res.data.list.length
          });
          // 可以根据需要更新页面显示
          console.log('活动问题列表已加载:', res.data.list.length, '个问题');
        }
      })
      .catch(err => {
        console.error('获取活动问题列表失败:', err);
        wx.showToast({
          title: '活动问题列表加载失败',
          icon: 'none'
        });
      })
      .finally(() => {
        wx.hideLoading();
      });
  },

  /**
   * 更新选项选中状态数组
   * @param {number} selectedOption 单选题选中的选项索引
   * @param {array} selectedOptions 多选题选中的选项索引数组
   * @returns {array} 更新后的选中状态数组
   */
  updateSelectedClass: function (selectedOption, selectedOptions) {
    const optionsCount = this.data.currentQuestion ? this.data.currentQuestion.options.length : 0;
    const selectedClass = [];
    const questionTypeCode = this.data.questionTypeCode;

    for (let i = 0; i < optionsCount; i++) {
      if (questionTypeCode === 0) {
        // 单选题逻辑
        selectedClass.push(i === selectedOption ? 'selected' : '');
      } else if (questionTypeCode === 1) {
        // 多选题逻辑
        selectedClass.push(selectedOptions && selectedOptions.indexOf(i) > -1 ? 'selected' : '');
      } else {
        selectedClass.push('');
      }
    }

    return selectedClass;
  },



  /**
   * 获取或创建答题卡
   * 当没有直接的answerCardId时，根据传入的参数创建或获取对应的答题卡
   */
  getOrCreateAnswerCard: async function () {
    const { subjectId, chapterId, questionIndex } = this.data;

    // 显示加载提示
    wx.showLoading({
      title: '准备答题卡...',
      mask: true
    });

    try {
      // 确定答题卡类型
      let cardType = 'knowledge'; // 默认知识点类型
      if (chapterId) {
        cardType = 'chapter'; // 如果有章节ID，则为章节类型
      }

      // 构建API参数
      const apiParams = {
        subjectId: subjectId,
        chapterId: chapterId,
        cardType: cardType,
        questionIndex: questionIndex || 0
      };

      // 对于知识点类型的答题卡，可以尝试从选项中获取问题id列表
      // 注意：这里可能需要根据实际情况调整，因为dati页面可能没有完整的问题列表
      // 但为了API调用的一致性，我们保留这个字段的可能性
      if (cardType === 'knowledge' && this.data.questions && Array.isArray(this.data.questions)) {
        apiParams.questionIds = this.data.questions.map(q => q.id);
      }

      // 调用API获取或创建答题卡
      const res = await app.api.getOrCreateAnswerCard(apiParams);

      if (res && res.code === 200 && res.data && res.data.card_id) {
        // 更新答题卡ID
        this.setData({
          answerCardId: res.data.card_id
        });

        // 加载答题卡详情
        await this.loadAnswerCardDetail();
      }
    } catch (error) {
      wx.showToast({
        title: '答题卡创建失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },

  // 打开纠错弹窗
  openJiucuoModal: function () {
    this.setData({
      showJiucuoModal: true
    });
  },

  // 关闭纠错弹窗
  closeJiucuoModal: function () {
    this.setData({
      showJiucuoModal: false
    });
  },

  // 打开答题卡弹窗
  openDatikaModal: function () {
    // 如果有答题卡ID，先加载答题卡详情数据
    if (this.data.answerCardId) {
      this.loadAnswerCardDetail().then(() => {
        // 数据加载完成后显示弹窗
        this.setData({
          showDatikaModal: true
        });

        // 强制更新答题卡组件数据，确保组件接收到最新数据
        setTimeout(() => {
          // 通过设置相同的值来触发observers监听
          this.setData({
            answerRecords: [...this.data.answerRecords]
          });
        }, 100);
      }).catch(err => {
        // 即使加载失败也显示弹窗，但使用默认数据
        this.setData({
          showDatikaModal: true
        });
      });
    } else {
      // 没有答题卡ID，直接显示弹窗
      this.setData({
        showDatikaModal: true
      });
    }
  },

  // 关闭答题卡弹窗
  closeDatikaModal: function () {
    this.setData({
      showDatikaModal: false
    });
  },

  // 跳转到指定题目
  goToQuestion: function (e) {
    const { questionId, type } = e.detail;

    // 更新当前题目ID并加载题目详情
    if (questionId) {
      this.setData({
        questionId: questionId,
        selectedOption: null,
        isAnswered: false,
        isCorrect: false,
        userAnswer: null
      });

      // 加载新的题目详情
      this.loadQuestionDetail();

      // 关闭答题卡弹窗
      this.closeDatikaModal();
    }
  },

  // 打开评论弹窗
  openPinglunModal: function () {
    this.setData({
      showPinglunModal: true
    });
  },

  // 时间格式化函数
  formatTime: function (timestamp) {
    if (!timestamp) return '';

    // 如果是时间戳格式（秒级或毫秒级）
    if (typeof timestamp === 'number' || /^\d+$/.test(timestamp)) {
      // 判断是秒级时间戳还是毫秒级时间戳
      let date;
      if (timestamp > 1000000000000) {
        // 毫秒级时间戳
        date = new Date(parseInt(timestamp));
      } else {
        // 秒级时间戳
        date = new Date(parseInt(timestamp) * 1000);
      }

      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      const seconds = date.getSeconds().toString().padStart(2, '0');

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }

    // 如果是字符串格式，尝试直接返回
    if (typeof timestamp === 'string') {
      // 如果是ISO格式的时间字符串
      if (timestamp.includes('T') && timestamp.includes('Z')) {
        const date = new Date(timestamp);
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        const hours = date.getHours().toString().padStart(2, '0');
        const minutes = date.getMinutes().toString().padStart(2, '0');
        const seconds = date.getSeconds().toString().padStart(2, '0');

        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      }

      // 如果已经是格式化的时间字符串，直接返回
      if (/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(timestamp)) {
        return timestamp;
      }

      // 如果是字符串格式的时间戳
      if (/^\d+$/.test(timestamp)) {
        let date;
        if (timestamp.length > 10) {
          // 毫秒级时间戳
          date = new Date(parseInt(timestamp));
        } else {
          // 秒级时间戳
          date = new Date(parseInt(timestamp) * 1000);
        }

        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        const hours = date.getHours().toString().padStart(2, '0');
        const minutes = date.getMinutes().toString().padStart(2, '0');
        const seconds = date.getSeconds().toString().padStart(2, '0');

        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      }
    }

    // 其他情况返回原始值
    return timestamp;
  },

  // 加载评论列表
  loadCommentList: function () {
    const that = this;
    const { questionId, commentPage, commentLimit } = this.data;

    if (!questionId) {
      return;
    }

    // 设置加载状态
    this.setData({
      commentLoading: true
    });

    // 调用API获取评论列表
    app.api.getCommentList({
      questionId: questionId,
      page: commentPage,
      limit: commentLimit
    }).then(res => {
      if (res && res.code === 200 && res.data) {
        const commentData = res.data;

        // 格式化评论数据
        const formattedComments = commentData.data.map(comment => ({
          id: comment.id,
          content: comment.content,
          likeCount: comment.like_count || 0,
          createTime: that.formatTime(comment.created_at),
          user: comment.user || {
            id: 0,
            nickname: '匿名用户',
            avatar: 'https://exam-1304576422.cos.ap-guangzhou.myqcloud.com/static/default_avatar.png'
          }
        }));
        console.log(commentData.data)
        let answerRecords = JSON.parse(JSON.stringify(this.data.answerRecords))
        console.log(answerRecords)
        console.log(this.data.currentBannerIndex)
        answerRecords[this.data.currentBannerIndex].commentList = formattedComments
        console.log(answerRecords)
        that.setData({
          answerRecords: answerRecords,
          commentList: formattedComments,
          commentTotal: commentData.total || 0,
          commentLoading: false
        });
        console.log(this.data.answerRecords)
      } else {
        that.setData({
          commentLoading: false
        });
      }
    }).catch(err => {
      console.error('加载评论列表失败:', err);
      that.setData({
        commentLoading: false
      });

      // 如果加载失败，显示默认评论数据
      that.setDefaultCommentData();
    });
  },

  // 设置默认评论数据
  setDefaultCommentData: function () {
    const defaultComments = [
      {
        id: 1,
        content: '这道题很有代表性，考察了核心知识点',
        likeCount: 5,
        createTime: '2024-01-15 10:30:00',
        user: {
          id: 1,
          nickname: '学习达人',
          avatar: 'https://exam-1304576422.cos.ap-guangzhou.myqcloud.com/static/default_avatar.png'
        }
      },
      {
        id: 2,
        content: '选项C的干扰性很强，容易选错',
        likeCount: 3,
        createTime: '2024-01-14 15:20:00',
        user: {
          id: 2,
          nickname: '学霸小张',
          avatar: 'https://exam-1304576422.cos.ap-guangzhou.myqcloud.com/static/default_avatar.png'
        }
      }
    ];

    this.setData({
      commentList: defaultComments,
      commentTotal: defaultComments.length
    });
  },

  // 关闭评论弹窗
  closePinglunModal: function () {
    this.setData({
      showPinglunModal: false
    });
  },

  // 处理评论提交
  handlePinglunSubmit: function (e) {
    const { content, commentId } = e.detail;
    console.log('收到评论内容:', content, '评论ID:', commentId);

    // 评论组件已经调用了API，这里只需要重新加载评论列表显示最新评论
    const questionId = this.data.questionId || this.data.currentQuestionId;
    this.loadCommentList(questionId);
  },

  // 点赞评论
  likeComment: function (e) {
    const commentId = e.currentTarget.dataset.commentId;
    const questionId = this.data.questionId || this.data.currentQuestionId;
    const that = this;

    if (!commentId || !questionId) {
      return;
    }

    // 调用API点赞评论
    app.api.likeComment({
      commentId: commentId
    }).then(res => {
      if (res && res.code === 200) {
        // 点赞成功，更新本地评论列表
        const questionIndex = that.data.answerRecords.findIndex(record => record.questionId === questionId);
        if (questionIndex !== -1 && that.data.answerRecords[questionIndex].commentList) {
          const newAnswerRecords = [...that.data.answerRecords];
          newAnswerRecords[questionIndex].commentList = newAnswerRecords[questionIndex].commentList.map(comment => {
            if (comment.id === commentId) {
              return {
                ...comment,
                likeCount: comment.likeCount + 1
              };
            }
            return comment;
          });

          that.setData({
            answerRecords: newAnswerRecords
          });
        }

        wx.showToast({
          title: '点赞成功',
          icon: 'success'
        });
      } else {
        wx.showToast({
          title: '点赞失败',
          icon: 'none'
        });
      }
    }).catch(err => {
      console.error('点赞评论失败:', err);
      wx.showToast({
        title: '网络错误',
        icon: 'none'
      });
    });
  },

  // 处理wenda组件发表评论
  handleWendaPublishComment: function (e) {
    const { content, messageIndex } = e.detail;
    const currentIndex = this.data.currentBannerIndex;

    if (currentIndex === undefined || currentIndex < 0) {
      wx.showToast({
        title: '当前题目索引错误',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    // 检查当前索引是否在answerRecords范围内
    if (currentIndex >= this.data.answerRecords.length) {
      wx.showToast({
        title: '题目索引超出范围',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    // 创建新评论对象
    const newComment = {
      id: Date.now(), // 使用时间戳作为临时ID
      content: content,
      likeCount: 0,
      createTime: this.formatTime(new Date()),
      user: {
        id: 0, // 默认用户ID
        nickname: 'AI助手',
        avatar: 'https://exam-1304576422.cos.ap-guangzhou.myqcloud.com/static/default_avatar.png'
      }
    };

    // 更新answerRecords中的评论列表
    const newAnswerRecords = [...this.data.answerRecords];
    if (!newAnswerRecords[currentIndex].commentList) {
      newAnswerRecords[currentIndex].commentList = [];
    }
    newAnswerRecords[currentIndex].commentList.unshift(newComment); // 添加到评论列表开头

    // 更新显示评论状态
    const showComments = { ...this.data.showComments };
    showComments[currentIndex] = true;

    this.setData({
      answerRecords: newAnswerRecords,
      showComments: showComments
    });
  },

  /**
   * 处理纠错提交
   */
  handleJiucuoSubmit: function () {
    if (!this.data.feedbackContent.trim()) {
      wx.showToast({
        title: '请输入纠错内容',
        icon: 'none'
      });
      return;
    }

    const that = this;
    app.api.submitFeedback({
      questionId: this.data.questionId,
      content: this.data.feedbackContent
    }).then(res => {
      wx.showToast({
        title: '提交成功',
        icon: 'success'
      });
      // 清空内容并关闭弹窗
      that.setData({
        feedbackContent: '',
        showJiucuoModal: false
      });
    }).catch(err => {
      console.error('提交纠错失败:', err);
    });
  },

  /**
   * 输入纠错内容
   */
  onFeedbackInput: function (e) {
    this.setData({
      feedbackContent: e.detail.value
    });
  },

  /**
   * 重做功能
   */
  redoQuestion: function () {
    // 重置答题状态
    this.setData({
      selectedOption: null,
      selectedOptions: [],
      isAnswered: false,
      isCorrect: false,
      userAnswer: null,
      submitButtonText: this.data.questionTypeCode <= 1 ? '提交答案' : '显示答案'
    });
    console.log('重做题目');

  },

  /**
   * 格式化时间
   */
  formatTime: function (date) {
    if (!date) return '';

    // 如果是时间戳或字符串，转换为Date对象
    if (typeof date === 'number' || typeof date === 'string') {
      date = new Date(date);
    }

    // 检查是否为有效的Date对象
    if (!(date instanceof Date) || isNaN(date.getTime())) {
      return '';
    }

    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    const seconds = date.getSeconds().toString().padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  },

  /**
   * 简单的Markdown解析函数 - 处理标题、加粗和换行
   */
  parseMarkdown: function (text) {
    if (!text) return '';

    let parsed = text;

    // 将 ### 标题 转换为 <h3>标题</h3>
    parsed = parsed.replace(/###\s+(.*?)(?=\n|$)/g, '<h3>$1</h3>');

    // 将 **文本** 转换为 <strong style="color: #9b1e23;">文本</strong>
    parsed = parsed.replace(/\*\*(.*?)\*\*/g, '<strong style="color: #9b1e23;">$1</strong>');

    // 将 \n 转换为 <br/>
    parsed = parsed.replace(/\n/g, '<br/>');

    return parsed;
  },

  /**
   * 调用AI问答接口
   */
  callAIChat: function (message) {
    const that = this;

    // 创建AI消息对象（用于流式传输）- 直接显示"正在思考中..."
    const aiMessage = {
      type: 'ai',
      content: '正在思考中...',
      parsedContent: '正在思考中...',
      time: that.formatTime(new Date()),
      isStreaming: true // 标记为流式传输中
    };

    // 先将AI消息添加到消息列表
    that.setData({
      messages: [...that.data.messages, aiMessage]
    }, () => {
      // 滚动到底部
      that.scrollToBottom();
    });

    const app = getApp();
    wx.request({
      url: app.globalData.baseUrl + '/frontend/ai/chat',
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('userToken') || ''
      },
      timeout: 60000, // 设置60秒超时时间
      data: {
        message: message,
        questionId: this.data.questionId,
        isFirstQuestion: this.data.isFirstQuestion ? 1 : 0,
        stream: 1 // 启用流式传输
      },
      success: function (res) {
        if (res.data.code === 200) {
          // 模拟流式效果：逐字显示内容
          const fullContent = res.data.data.content || '';
          const messages = that.data.messages;
          const lastIndex = messages.length - 1;

          // 延迟一小段时间后开始显示真实内容（让用户看到"正在思考中..."）
          setTimeout(() => {
            // 模拟逐字显示效果
            let currentIndex = 0;
            const typingInterval = setInterval(() => {
              if (currentIndex < fullContent.length) {
                const currentContent = fullContent.substring(0, currentIndex + 1);
                messages[lastIndex] = {
                  ...messages[lastIndex],
                  content: currentContent,
                  parsedContent: that.parseMarkdown(currentContent)
                };

                that.setData({
                  messages: messages
                }, () => {
                  that.scrollToBottom();
                });

                currentIndex++;
              } else {
                clearInterval(typingInterval);

                // 流式传输完成
                messages[lastIndex] = {
                  ...messages[lastIndex],
                  isStreaming: false
                };

                that.setData({
                  messages: messages,
                  isLoading: false,
                  isFirstQuestion: false
                });
              }
            }, 30); // 每30ms显示一个字符
          }, 500);
        } else {
          // 处理错误情况
          const messages = that.data.messages;
          messages[messages.length - 1] = {
            ...messages[messages.length - 1],
            content: res.data.message || '服务器错误，请稍后重试',
            parsedContent: res.data.message || '服务器错误，请稍后重试',
            isStreaming: false
          };

          that.setData({
            messages: messages,
            isLoading: false
          });
        }
      },
      fail: function (error) {
        console.error('AI聊天请求失败:', error);

        const messages = that.data.messages;
        messages[messages.length - 1] = {
          ...messages[messages.length - 1],
          content: '网络错误，请检查网络连接后重试',
          parsedContent: '网络错误，请检查网络连接后重试',
          isStreaming: false
        };

        that.setData({
          messages: messages,
          isLoading: false
        });
      }
    });
  },

  /**
   * 滚动到底部
   */
  scrollToBottom: function () {
    wx.createSelectorQuery().select('.ulss').boundingClientRect((rect) => {
      if (rect) {
        wx.createSelectorQuery().select('.ulss').scrollOffset((res) => {
          wx.createSelectorQuery().select('.ulss').context((context) => {
            context.context.scrollTo({
              scrollTop: res.scrollTop + rect.height + 100,
              duration: 300
            });
          }).exec();
        }).exec();
      }
    }).exec();
  },

  /**
   * 输入框内容变化
   */
  onInputChange: function (e) {
    this.setData({
      inputValue: e.detail.value
    });
  },

  /**
   * 发送消息
   */
  sendMessage: function (e) {
    const jiexi = e.currentTarget.dataset.jiexi || '';
    if (!jiexi) {
      wx.showToast({
        title: '题目信息加载中',
        icon: 'none'
      });
      return;
    }

    const message = "解析下这个题目：" + jiexi;

    // 重置消息列表，只保留当前解析
    this.setData({
      messages: []
    });

    this.setData({
      isLoading: true,
      inputValue: ''
    });

    // 添加用户消息
    const userMessage = {
      type: 'user',
      content: message,
      time: this.formatTime(new Date())
    };

    this.setData({
      messages: [...this.data.messages, userMessage]
    }, () => {
      // 滚动到底部显示用户消息
      this.scrollToBottom();
    });

    // 调用AI问答接口
    this.callAIChat(message);
  },

  /**
   * 跳转到活动答题页面
   */
  goToActivityQuiz: function () {
    // 显示加载提示
    wx.showLoading({
      title: '检查答题资格...',
    });
    
    // 调用接口检查用户答题次数
    getApp().api.getActivityResult({activity_id: 1}).then(res => {
      wx.hideLoading();
      
      if (res.code === 200) {
        // 检查是否已达到最大参与次数
        if (res.data.has_reached_max_attempts) {
          // 已达到最大次数，显示提示
          this.setData({
            showmsg: true,
            massges: "您已达到最大参与次数（2次）",
          });
          setTimeout(() => {
            this.setData({
              showmsg: false,
              massges: "",
            });
          }, 2000);
        } else {
          // 未达到最大次数，显示确认弹窗
          this.setData({
            types: "活动答题",
            showtan: true,
            tishititle: "温馨提示",
            tishimessage: `每人最多答题两次!\n您还剩余${res.data.remaining_attempts}次答题机会。`,
          });
        }
      } else if (res.msg === '请先登录') {
        // 用户未登录，跳转到登录页面
        wx.showToast({
          title: '请先登录',
          icon: 'none',
          duration: 1500
        });
        // 这里可以添加登录页面跳转逻辑
      } else {
        // 其他错误情况
        this.setData({
          showmsg: true,
          massges: "检查失败，请重试",
        });
        setTimeout(() => {
          this.setData({
            showmsg: false,
            massges: "",
          });
        }, 1500);
      }
    }).catch(err => {
      wx.hideLoading();
      console.error('检查答题次数失败:', err);
      this.setData({
        showmsg: true,
        massges: "网络错误，请重试",
      });
      setTimeout(() => {
        this.setData({
          showmsg: false,
          massges: "",
        });
      }, 1500);
    });
  }
});
